<template>
  <div class="login-container">
    <el-card v-loading="loading" class="login-card">
      <div class="login-form">
        <el-form :model="loginForm" label-position="top">
          <el-form-item :label="$t('userName')">
            <el-input v-model="loginForm.username" maxlength="20" />
          </el-form-item>
          <el-form-item :label="$t('password')">
            <el-input
              type="password"
              maxlength="20"
              v-model="loginForm.password"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin">{{ $t('login') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ElButton, ElCard, ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import { login } from '@/api/user'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()


let loading = ref(false)

const router = useRouter()

const loginForm = ref({
  username: 'admin',
  password: 'admin'
})

const handleLogin = () => {
  if (!loginForm.value.username || !loginForm.value.password) {
    ElMessage.error(t('userNamePwdEmpty'))
    return
  }
  loading.value = true
  login(loginForm.value.username, loginForm.value.password)
    .then((res: any) => {
      loading.value = false
      localStorage.setItem('userName', res.backend_user_name)
      localStorage.setItem('userId', res.backend_user_id)
      ElMessage.success(t('loginSuccess'))
      router.replace({ name: 'orderList' })
      // window.location.href = '/welcome'
    })
    .catch((err: any) => {
      loading.value = false
    })

  // console.log("【登录成功-cookie】",document.cookie)
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: white;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-form {
  margin: 0 auto;
}
</style>
